package com.coder520.sync_learning.demo.hookTest;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Set;
import java.util.concurrent.TimeUnit;
public class PreventDuplicated {
    private final static  String LOCK_PATH="D:\\home\\zhaoyibo\\locks\\" +
            "";

    private final static  String LOCK_FILE=".lock";

    private final static  String PERMISSIONS="rw-------";

    public static void main(String[] args) throws IOException {
        //注入hook线程，在线成结束之后删除掉文件
        Runtime.getRuntime().addShutdownHook(new Thread(()->{
            System.out.println("这个程序将会收到删除的信号");
            getlockFile().toFile().delete();
        }));


        //检查是否存在lock文件
       // checkedRunning();


    }

    private static void checkedRunning() throws IOException {
        Path path=getlockFile();

        if (path.toFile().exists()){
            throw new RuntimeException("这个程序将要运行");
        }

        Set<PosixFilePermission> perms= PosixFilePermissions.fromString(PERMISSIONS);

        Files.createFile(path,PosixFilePermissions.asFileAttribute(perms));

    }

    private static Path getlockFile() {
        return Paths.get(LOCK_PATH,LOCK_FILE);
    }
}
